<?php
/**
 * storage items in a object
 */

namespace shine\storage;

use Countable;
use ArrayIterator;
use IteratorAggregate;

/**
 * @package storage
 * @author lixin_gg@126.com
 * @static
 */
class Storage implements IteratorAggregate, Countable
{
    /**
     * storage property
     * @var array
     */
    protected $data = [];

    /**
     * constructor
     * @param array $items items to storage must associate by key
     */
    public function __construct(array $items = [])
    {
        $this->data = $items;
    }

    /**
     * get item
     * @param mixed $key storage key
     * @return mixed
     */
    public function get($key)
    {
        return $this->data[$key] ?? null;
    }

    /**
     * set item
     * @param mixed $key storage key
     * @param mixed $item storage item
     * @return void
     */
    public function set($key, $item): void
    {
        $this->data[$key] = $item;
    }

    /**
     * whether contains the key
     * @param mixed $key storage key
     * @return boolean
     */
    public function contains($key): bool
    {
        return isset($this->data[$key]);
    }

    /**
     * unset item by key
     * @param mixed $key
     * @return void
     */
    public function unset($key): void
    {
        unset($this->data[$key]);
    }
    
    /**
     * get array iterator instance
     * @inheritDoc
     * @return ArrayIterator
     */
    public function getIterator() : ArrayIterator
    {
        return new ArrayIterator($this->data);
    }

    /**
     * @inheritDoc
     * @return integer
     */
    public function count(): int
    {
        return count($this->data);
    }
}